<template>
    <div>
        <!-- 表格操作项 start  -->
        <Button v-for="(item, index) in tableBtn" :key="index" type="primary" :icon="item.icon" class="ivu-mr-8"
            @click="tableTopOperate(item.name)">{{ item.label }}</Button>
        <!-- <Button icon="md-list"
              class="ivu-ml-8"
              v-show="tableBatchBtns && tableBatchBtns.length>0 && tableSelectData &&tableSelectData.length">批量操作</Button> -->
        <Dropdown class="ivu-ml-8" @on-click="handleClickItem">
            <Button>更多操作
                <Icon type="ios-arrow-down" />
            </Button>
            <DropdownMenu slot="list">
                <DropdownItem
                  v-for="(item, index) in tableBatchBtns"
                  :key="index" :name="item.name"
                  :disabled="tableSelectData.length == 0"
                >{{item.label}}
                </DropdownItem>
            </DropdownMenu>
        </Dropdown>
        <Modal @on-ok="handleSubmit"  title="新增属性值" v-model="shipmentsFlag">
            <div style="width:60%;margin: 0 auto;">
                <Form :model="formLeft" label-position="right" :label-width="100">
                    <!-- <FormItem label="值">
              <Input v-model="formLeft.input1"></Input>
            </FormItem> -->
                    <!-- <FormItem label="非展示值">
              <Input v-model="formLeft.input2"></Input>
            </FormItem>-->
                    <FormItem label="所属分类">
                        <Select v-model="model1" style="width:200px">
                            <Option v-for="item in cityList" :value="item.uuid" :key="item.uuid">{{ item.categoryName}}
                            </Option>
                        </Select>
                    </FormItem>
                    <FormItem label="自定义" v-if="model1==='storeSpec'">
                        <Input maxlength="50" show-word-limit v-model="formLeft.storeSpec"></Input>
                    </FormItem>
                    <FormItem label="颜色属性" v-if="model1==='color'">
                        <Input maxlength="50" show-word-limit v-model="formLeft.color"></Input>
                    </FormItem>
                    <FormItem label="星期" v-if="model1==='week'">
                        <Select v-model="model2" style="width:200px">
                            <Option v-for="item in weekList" :value="item.value" :key="item.value">{{ item.label }}
                            </Option>
                        </Select>
                    </FormItem>
                    <FormItem label="时间" v-if="model1==='time'">
                        <Col span="12">
                        <TimePicker v-model="model3" confirm type="timerange" placement="bottom-end"
                            placeholder="Select time" style="width: 168px"></TimePicker>
                        </Col>
                    </FormItem>
                    <FormItem label="自定义"
                        v-if="model1!=='time'&&model1!=='color'&&model1!=='storeSpec'&&model1!=='week'&&model1!==''">
                        <Input maxlength="50" show-word-limit v-model="formLeft.storeSpec"></Input>
                    </FormItem>
                    <!-- <FormItem label="图片">
              <div class="img"></div>
              <div style="font-size: 10px">
                <Upload action="//jsonplaceholder.typicode.com/posts/">
                  <Button>选择图片</Button>
                </Upload>
              </div>
            </FormItem> -->
                    <!-- <FormItem label="">
              <Button type="primary" :loading="sLoading" @click="handleSubmit('formData')">提交</Button>
              <Button style="margin-left: 8px" @click="cancel">取消</Button>
            </FormItem> -->

                    <FormItem label="">
                    </FormItem>
                </Form>
            </div>
        </Modal>
        <!-- 表格操作项 end  -->
        <!-- 关联属性 -->
        <Modal v-model="showAttributeModal" fullscreen footer-hide title="关联属性值">
            <Card :bordered="false" dis-hover class="ivu-mt qw-form-card">
                <!-- 自定义筛选项 start  -->
                <Form ref="attributeForm" :model="attributeFromData" :label-width="80" inline @submit.native.prevent>
                    <FormItem label="属性值">
                        <Input v-model="attributeFromData.value" placeholder="请输入属性值"
                            @on-enter="handleAttributeSubmit('attributeForm')"></Input>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleAttributeSubmit('attributeForm')">查询</Button>
                        <Button @click="handleAttributeReset('attributeForm')" class="ivu-ml">清空</Button>
                    </FormItem>
                </Form>
                <!-- 自定义筛选项 end  -->
            </Card>
            <Card :bordered="false" dis-hover class="ivu-mt">
                <Button type="primary" class="ivu-ml" @click="relevance()">批量关联</Button>
                <Button type="primary" class="ivu-ml" @click="addAttribute()">新增属性值</Button>
            </Card>
            <Card :bordered="false" dis-hover class="ivu-mt">
                <!-- 调用表格子组件 start  -->
                <Table stripe ref="attributeTable" :loading="NoRelAttributeLoading" :columns="attributeListColums"
                    :data="NoRelAttributeListData" @on-select="handleSelect" @on-select-all='handleSelectAll'>
                    <template slot-scope="{ row }" slot="action">
                        <a @click="toRelation(row.uuid,'all')">关联</a>
                    </template>
                </Table>
                <!-- 分页 start  -->
                <div class="ivu-mt ivu-text-center">
                    <Page :total="NoRelAttributeTotalNum" show-total show-sizer :current.sync="NoRelAttributeNowPage"
                        @on-change="getNoRelAttributeList" @on-page-size-change="NoRelAttributeChangePage" />
                </div>
                <!-- 分页 end  -->
                <!-- 调用表格子组件 end  -->
            </Card>
        </Modal>
        <!-- 关联属性 end -->
    </div>
</template>
<script>
import dynamictablebtns from '@/mixins/dynamictablebtns'; // 混入通用代码
import { ApiRequest } from '@api/basePage';

export default {
  mixins: [dynamictablebtns],
  data () {
    return {
      uuids: [], // 批量关联id
      row: '',
      // 品牌列表
      attributeListColums: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '属性值名称',
          key: 'value',
          minWidth: 300
        },
        {
          title: '属性值编码',
          key: 'uuid',
          minWidth: 300
        },
        {
          title: '属性值分类',
          key: 'categoryName',
          minWidth: 300
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          minWidth: 80
        }
      ],
      attributeListData: [],
      // 打开关联属性弹窗
      showAttributeModal: false,
      attributeFromData: {
        value: '',
        value_q: 'Like'
      },
      NoRelAttributeLoading: true,
      NoRelAttributeListData: [],
      NoRelAttributeTotalNum: 0,
      NoRelAttributeNowPage: 1,
      NoRelAttributePageShow: 10,
      shipmentsFlag: false,
      formLeft: {
        storeSpec: '',
        color: '',
        input3: '',
        desc: ''
      },
      weekList: [
        {
          value: '星期一',
          label: '星期一'
        },
        {
          value: '星期二',
          label: '星期二'
        },
        {
          value: '星期三',
          label: '星期三'
        },
        {
          value: '星期四',
          label: '星期四'
        },
        {
          value: '星期五',
          label: '星期五'
        },
        {
          value: '星期六',
          label: '星期六'
        },
        {
          value: '星期日',
          label: '星期日'
        }
      ],
      cityList: [],
      model1: '',
      model2: '',
      model3: ''
    };
  },
  methods: {
    // 表格操作项事件
    tableTopOperate (name) {
      if (name === 'relation') {
        this.openAttributeModal();
      }
      if (name === 'attributeViewSubmit') {
        if (this.tableSelectData.length == 0) {
          this.$Message.warning('请选择');
          return;
        }
        this.handleClickItem('attributeViewSubmit');
      }
      if (name === 'attributeViewClose') {
        this.$router.push({ name: 'attributeList' });
      }
    },
    handleSelect (row) {
      this.row = row;
    },
    handleSelectAll (row) {
      this.row = row;
    },
    addAttribute () {
      let data = {};
      ApiRequest(
        '/sysback/template/producttemplateattrvaluecategory/getAllAttrValueCategory',
        'post',
        data
      ).then(res => {
        let data = res.retData;
        this.cityList = data;
        this.shipmentsFlag = true;
      });
    },
    handleSubmit () {
      let data = {
        attrUuid: this.$route.query.uuid
      };
      if (this.model1 === 'storeSpec') {
        if (this.formLeft.storeSpec !== '') {
          data.value = this.formLeft.storeSpec;
          data.categoryUuid = 'storeSpec';
        } else {
          this.$Message.error('请填写自定义内容');
          return;
        }
      } else if (this.model1 === 'color') {
        if (this.formLeft.color !== '') {
          data.value = this.formLeft.color;
          data.categoryUuid = 'color';
        } else {
          this.$Message.error('请填写颜色属性');
          return;
        }
      } else if (this.model1 === 'week') {
        if (this.model2 !== '') {
          data.value = this.model2;
          data.categoryUuid = 'week';
        } else {
          this.$Message.error('请选择星期');
          return;
        }
      } else if (this.model1 === 'time') {
        if (this.model3[0] !== '' && this.model3[1] !== '') {
          data.categoryUuid = 'time';
          data.value = this.model3[0] + '-' + this.model3[1];
        } else {
          this.$Message.error('请选择时间');
          return;
        }
      } else {
        if (this.formLeft.storeSpec !== '') {
          data.value = this.formLeft.storeSpec;
          data.categoryUuid = this.model1;
        } else {
          this.$Message.error('请填写自定义内容');
          return;
        }
      }

      if (this.sLoading) {
        return false;
      }
      this.sLoading = true;
      // 开始请求会员信息
      ApiRequest(
        '/sysback/template/producttemplateattrvalue/createRelAttrValue',
        'post',
        data
      ).then(res => {
        if (res.retStatus === '1') {
          this.$Message.success('成功!');
          this.getNoRelAttributeList();
          this.actionsChange();
          // this.showAttributeModal = false;
          // this.$router.go(-1)
        }
        this.sLoading = false;
      });
    },
    relevance () {
      this.uuids = [];
      this.row.forEach(item => {
        this.uuids.push(item.uuid);
      });

      this.$Modal.confirm({
        title: '批量关联',
        content: '确定要批量关联选中的吗？',
        onOk: () => {
          let data = {
            attrValueUuids: this.uuids.join(','),
            attrUuid: this.$route.query.uuid
          };
          // 开始请求商品列表
          ApiRequest(
            this.requestApi.toRelationAttribute.url,
            this.requestApi.toRelationAttribute.type,
            data,
            true
          ).then(res => {
            if (res.retStatus === '1') {
              this.$Message.success('关联成功');
              this.getNoRelAttributeList();
              this.actionsChange();
            }
          });
        }
      });
    },
    handleClickItem (name) {
      if (name === 'delete') {
        let uuidArr = [];
        this.tableSelectData.forEach(item => {
          uuidArr.push(item.uuid);
        });
        let data = {
          uuids: uuidArr.join(',')
        };
        // 开始请求列表
        ApiRequest(
          this.requestApi.delTableList.url,
          this.requestApi.delTableList.type,
          data,
          true
        ).then(res => {
          if (res.retStatus === '1') {
            this.$Message.success('批量删除成功');
            this.tableSelectData = [];
            this.actionsChange();
          }
        });
      } else if (name === 'disassociation') {
        let uuid = this.$route.query.uuid;
        this.$Modal.confirm({
          title: '取消关联',
          content: '确定取消关联吗？',
          onOk: () => {
            let uuidArr = [];

            this.tableSelectData.forEach(item => {
              uuidArr.push(item.uuid);
            });
            let data = {
              uuids: uuidArr.join(','),
              attrUuid: uuid
            };
            // 开始请求商品列表
            ApiRequest(
              this.requestApi.delRelationAttribute.url,
              this.requestApi.delRelationAttribute.type,
              data,
              true
            ).then(res => {
              this.$Message.success('取消成功');
              this.actionsChange();
            });
          }
        });
      } else if (name === 'attributeViewSubmit') {
        let uuidArr = [];
        this.tableSelectData.forEach(item => {
          uuidArr.push(item.uuid + '|' + item.position);
        });
        this.$Modal.confirm({
          title: '批量更新',
          content: '确定要批量更新吗？',
          onOk: () => {
            let data = {
              selectRelUuids: uuidArr.join(',')
            };

            // 开始请求列表
            ApiRequest(
              this.requestApi.renewTableList.url,
              this.requestApi.renewTableList.type,
              data,
              true
            ).then(res => {
              this.$Message.success('更新成功');
              this.tableSelectData = [];
              this.$router.go(0);
              // this.actionsChange()
              // this.$router.go(0)
            });
          }
        });
      }
    },
    // 打开展示属性的弹窗
    openAttributeModal () {
      this.showAttributeModal = true;
      this.getNoRelAttributeList();
    },
    // 获取全部属性列表
    getNoRelAttributeList () {
      let searchParam = [];
      Object.keys(this.attributeFromData).forEach(key => {
        searchParam.push({ name: key, value: this.attributeFromData[key] });
      });
      searchParam.push({ name: 'attrUuid', value: this.$route.query.uuid });
      searchParam.push({ name: 'attrUuid_s', value: 'EQ' });
      let data = {
        searchParam: JSON.stringify(searchParam),
        nowPage: this.NoRelAttributeNowPage,
        pageShow: this.NoRelAttributePageShow,
        sortName: '',
        sortType: ''
      };
      this.NoRelAttributeLoading = true;
      // 开始请求列表
      ApiRequest(
        this.requestApi.getNoRelAttribute.url,
        this.requestApi.getNoRelAttribute.type,
        data
      ).then(res => {
        let resData = {};
        if (res.retData && res.retData !== '') {
          resData = res.retData;
        }
        let listData = resData.results ? resData.results : [];
        listData.forEach(item => {
          for (let i = 0; i < this.attributeListData.length; i++) {
            let obj = this.attributeListData[i];
            if (item.uuid === obj.uuid) {
              item.chooseOrNo = 1;
              break;
            }
          }
        });
        this.NoRelAttributeListData = listData;
        this.NoRelAttributeTotalNum = resData.totalNum;
        this.NoRelAttributeLoading = false;
      });
    },
    // 全部属性 查询
    handleAttributeSubmit (name) {
      this.getNoRelAttributeList();
    },
    // 全部属性 -置空
    handleAttributeReset (name) {
      // this.$refs[name].resetFields();
      this.attributeFromData.value = '';
      this.getNoRelAttributeList();
    },
    // 全部属性切换分页
    NoRelAttributeChangePage (val) {
      this.NoRelAttributePageShow = val;
      this.$nextTick(() => {
        this.getNoRelAttributeList();
      });
    },
    // 关联属性
    toRelation (uuid, type) {
      this.$Modal.confirm({
        title: '关联属性',
        content: '确定要关联该属性吗？',
        onOk: () => {
          let data = {
            attrValueUuids: uuid,
            attrUuid: this.$route.query.uuid
          };
          // 开始请求商品列表
          ApiRequest(
            this.requestApi.toRelationAttribute.url,
            this.requestApi.toRelationAttribute.type,
            data,
            true
          ).then(res => {
            if (res.retStatus === '1') {
              this.$Message.success('关联成功');
              this.getNoRelAttributeList();
              this.actionsChange();
            }
          });
        }
      });
    }
  }
};
</script>
